﻿using System;
using System.Collections.Generic;
using System.Text;

using com.tiyma.data;
using com.tiyma.common;
using com.tiyma.model;
using Lucene.Net.Search;
using System.Web;
using System.IO;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Index;

namespace com.tiyma.components
{
    public partial class BookManager
    {
        BookDao m_boo_dao = new BookDao();

        /// <summary>
        /// 提交站点收录
        /// </summary>
        /// <param name="i_script"></param>
        /// <returns></returns>
        public string AddUserSite(string i_script)
        {
            if (string.IsNullOrEmpty(i_script))
                return "参数错误!";

            string[] t_site_arr = i_script.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

            if (t_site_arr != null && t_site_arr.Length != 5)
                return "参数错误!";
           
            Uri t_url = null;
            if (!Uri.TryCreate(t_site_arr[1], UriKind.RelativeOrAbsolute, out t_url))
                t_url = null;

            if (t_url == null)
                return "域名格式不符合规范";
            int t_pr=0;
            if(!int.TryParse(t_site_arr[2],out t_pr))
                t_pr=0;
            if(t_pr<=3)
                return "网站不符合收录条件!";

            string cookieVfCode = CookieManager.GetVifCode();
            //验证验证码
            string[] cookieVfArr = cookieVfCode.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
            if (cookieVfArr == null || cookieVfArr.Length != 3)
                return "验证码格式信息有误";

            //验证时间
            string vfCodeDt = cookieVfArr[0].ToString();
            DateTime dt = DateTime.Now;
            if (!DateTime.TryParse(vfCodeDt, out dt))
                dt = DateTime.MinValue;

            TimeSpan timeSpan = DateTime.Now.Subtract(dt);
            if (timeSpan.Seconds > 60)
                return "验证码已过期";

            //验证验证码信息
            if (string.Compare(t_site_arr[4], cookieVfArr[1].ToString(), true) != 0)
                return "验证码错误";

            if (string.Compare(SystemUtil.MD5Mac(t_site_arr[4] + Consts.VifCode), cookieVfArr[2].ToString(), true) != 0)
                return "验证码信息错误";

            try
            {
                Consts.ResultType t_ret = m_boo_dao.AddSite(SystemUtil.MSGFilterImport( t_site_arr[0]), string.Format("http://{0}", t_url.Host.ToLower()), t_pr,SystemUtil.MSGFilterImport(t_site_arr[3]));

                if (t_ret == Consts.ResultType.Successed)
                    return "提交成功，等待体验码小说网评估收录!";

                else if (t_ret == Consts.ResultType.Exists)
                    return "站点已经提交过了，请不要重复提交!";

                return "提交失败，请稍后重试!";

            }
            catch (Exception ex)
            {
                LogHelper.Error("添加站点信息失败" + ex.ToString());
                return "提交失败，请稍后重试!";
            }
        }

        /// <summary>
        /// 下架小说 1 书架小说 2 最近阅读小说
        /// </summary>
        /// <param name="i_book_name_list"></param>
        /// <param name="i_type"></param>
        /// <returns></returns>
        public bool DownBook(List<string> i_book_name_list, string i_type,long i_user_id)
        {
            try
            {
                if (i_type == "1")
                {
                    StringBuilder t_sb = new StringBuilder();
                    foreach (string t_book_name in i_book_name_list)
                    {
                        t_sb.AppendFormat("'{0}',",SystemUtil.MSGFilterImport(t_book_name));
                    }

                    int t_ret = m_boo_dao.DownBook(i_user_id, t_sb.ToString().TrimEnd(','));
                    if(t_ret>0)
                        return true;
                    return false;
                }
                else
                {
                    CookieManager.DeleteReadBook(i_book_name_list);
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("下架小说信息失败" + ex.ToString());
                return false;
            }
        }

          /// <summary>
        /// 添加书架
        /// </summary>
        /// <param name="i_user_id"></param>
        /// <param name="i_book_name"></param>
        /// <returns></returns>
        public string AddBookCase(long i_user_id, string i_book_name)
        {
            if (string.IsNullOrEmpty(i_book_name))
                return "参数错误!";
            i_book_name = SystemUtil.MSGFilterImport(i_book_name);
            try
            {
                Consts.ResultType t_ret = m_boo_dao.AddBookCase(i_user_id, i_book_name);

                if (t_ret == Consts.ResultType.Successed)
                    return "操作成功!";

                if (t_ret == Consts.ResultType.Exists)
                    return "本书已经在书架!";

                return "操作失败!";
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加书架小说失败" + ex.ToString());
                return "操作失败";
            }
        }


        /// <summary>
        /// 获取榜单数据
        /// </summary>
        /// <param name="i_type"></param>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public List<BookInfo> GetTopBook(int i_type, int i_count)
        {
           

            try
            {
                return m_boo_dao.GetTopBook(i_type, i_count);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取榜单数据失败" + ex.ToString());
                return null;
            }
        }

           /// <summary>
        /// 获取最新更新小说
        /// </summary>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public List<BookInfo> GetLastUpdateBook(int i_count)
        {
            try
            {
                return m_boo_dao.GetLastUpdateBook(i_count);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取最新更新小说失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取小说章节信息
        /// </summary>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        public ChapterInfo GetChapterInfo(long i_chapter_id, int i_site_id,out SiteInfo o_site_info,Consts.ChapterType i_chapter_type)
        {
            o_site_info = null;
            try
            {
                return m_boo_dao.GetChapterInfo(i_chapter_id, i_site_id, out o_site_info, i_chapter_type);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说章节信息失败" + ex.ToString());
                return null;
            }
        }

         /// <summary>
        /// 获取小说信息
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_table_name"></param>
        /// <param name="o_chapter_list"></param>
        /// <returns></returns>
        public BookInfo GetBookInfo(long i_book_id, out List<ChapterInfo> o_chapter_list)
        {
            o_chapter_list = null;

            if (i_book_id <= 0)
                return null;

           
            try
            {
                return m_boo_dao.GetBookInfo(i_book_id, out o_chapter_list);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说信息失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取最新更新小说 14条小说
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetLastUpdateBook()
        {
            //缓存两个小时
            string cacheKey = "last_update_book";

            List<BookInfo> t_list = null;

            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                t_list = HttpContext.Current.Cache[cacheKey] as List<BookInfo>;

                if (t_list != null && t_list.Count > 0)
                    return t_list;
            }
         
            try
            {
                t_list = m_boo_dao.GetLastUpdateBook();

              
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取最新更新小说失败" + ex.ToString());
            }

            if (t_list != null && t_list.Count>0)
            {

                HttpContext.Current.Cache.Insert(cacheKey, t_list, null, DateTime.Now.AddHours(2), TimeSpan.Zero);

                return t_list;
            }

            return null ;
           
        }

        /// <summary>
        /// 获取首页关键字列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetIndexKeyList()
        {
            List<string> t_list = null;
            try
            {
                string t_index_page_cache_key = "index_page_key_book";//首页关键字 缓存10天

                if (HttpContext.Current.Cache[t_index_page_cache_key] != null)
                {
                    t_list = HttpContext.Current.Cache[t_index_page_cache_key] as List<string>;

                    if (t_list != null && t_list.Count > 0)
                        return t_list;
                }

                List<BookInfo> t_book_list = GetDefaultRecommendBook();

                if (t_book_list != null && t_book_list.Count > 0)
                {
                    t_list = new List<string>();

                    foreach (BookInfo t_book in t_book_list)
                    {
                        t_list.Add(t_book.BookName);
                    }

                    HttpContext.Current.Cache.Insert(t_index_page_cache_key, t_list, null, DateTime.Now.AddDays(10), TimeSpan.Zero);

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取首页关键字列表失败" + ex.ToString());
            }

            return t_list;
        }


        /// <summary>
        /// 获取首页推荐小说
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetDefaultRecommendBook()
        {
            //缓存五个小时
            string cacheKey = "last_default_book";

  
            List<BookInfo> t_list = null;

            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                t_list = HttpContext.Current.Cache[cacheKey] as List<BookInfo>;

                if (t_list != null && t_list.Count > 0)
                    return t_list;
            }

            try
            {
                t_list = m_boo_dao.GetDefaultRecommendBook();


            }
            catch (Exception ex)
            {
                LogHelper.Error("获取首页推荐小说失败" + ex.ToString());
            }

            if (t_list != null && t_list.Count > 0)
            {

                HttpContext.Current.Cache.Insert(cacheKey, t_list, null, DateTime.Now.AddHours(5), TimeSpan.Zero);

                return t_list;
            }

            return null;
        }

        
        /// <summary>
        /// 获取首页右边文字推荐
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetRightRecommendBook()
        {
            //缓存五个小时
            string cacheKey = "last_recommend_right_book";

            List<BookInfo> t_list = null;

            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                t_list = HttpContext.Current.Cache[cacheKey] as List<BookInfo>;

                if (t_list != null && t_list.Count > 0)
                    return t_list;
            }

            try
            {
                t_list = m_boo_dao.GetRightRecommendBook();


            }
            catch (Exception ex)
            {
                LogHelper.Error("获取首页右边文字推荐" + ex.ToString());
            }

            if (t_list != null && t_list.Count > 0)
            {

                HttpContext.Current.Cache.Insert(cacheKey, t_list, null, DateTime.Now.AddHours(5), TimeSpan.Zero);

                return t_list;
            }

            return null;
        }

           /// <summary>
        /// 获取章节信息
        /// </summary>
        /// <param name="i_site_id"></param>
        /// <param name="i_book_id"></param>
        /// <param name="i_chapter_name"></param>
        /// <returns></returns>
        public ChapterInfo GetChapterInfo(int i_site_id, long i_book_id, string i_chapter_name, out SiteInfo o_site_info)
        {

            o_site_info = null;
            try
            {
                return m_boo_dao.GetChapterInfo(i_site_id, i_book_id, i_chapter_name, out o_site_info);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说章节失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取小说名称
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public string GetBookName(string i_book_id)
        {
            if(string.IsNullOrEmpty(i_book_id))
                return string.Empty;

            try
            {
                return m_boo_dao.GetBookName(i_book_id);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说信息失败" + ex.ToString());
                return string.Empty;
            }
        }

          /// <summary>
        /// 添加图书点击
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_exist_icon"></param>
        /// <returns></returns>
        public string AddBookClick(string i_script)
        {
            if(string.IsNullOrEmpty(i_script))
                return "参数异常";
            long t_book_id;
            string t_book_icon_url;
            int t_status = 1;

            string[] t_arr = i_script.Split(new char[] { '$' }, StringSplitOptions.None);
            if (t_arr == null || t_arr.Length != 3)
                return "参数异常";

            if (!long.TryParse(t_arr[0], out t_book_id))
                t_book_id = 0;

            if (t_book_id == 0)
                return "参数异常";

            t_book_icon_url = t_arr[1];

            if (!int.TryParse(t_arr[2], out t_status))
                t_status = 1;

            try
            {
                int t = 0;
                if (!string.IsNullOrEmpty(t_book_icon_url) && t_status!=(int)Consts.ExistsICON)
                {
                    if (t_book_icon_url.ToLower().IndexOf("mingshulou") > -1)
                        t_book_icon_url = "http://tiyma.com/images/noimg.jpg";

                    bool t_down_icon = NetSiteCatchManager.DownLoadFile(t_book_icon_url, Path.Combine(AppConfig.ICONPath, string.Format("{0}.jpg", t_book_id)));
                    if (t_down_icon)
                        t = (int)Consts.ExistsICON;
                }
                if (t_status == (int)Consts.ExistsICON)
                    t = (int)Consts.ExistsICON;

                int t_ret = m_boo_dao.AddBookClick(t_book_id, t);
                if (t_ret > 0)
                    return "操作成功";

                return "操作失败";
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加图书点击失败" + ex.ToString());
                return "操作失败";
            }
        }

        /// <summary>
        /// 获取该书同时收录的其他站点列表
        /// </summary>
        /// <param name="i_iste_id"></param>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public List<int> GetOtherSiteIdList(int i_iste_id, string i_book_name)
        {
            try
            {
                return m_boo_dao.GetOtherSiteIdList(i_iste_id, i_book_name);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说的其他收录站点列表失败" + ex.ToString());
                return null;
            }
        }

       
       
          /// <summary>
        /// 更新小说下载状态
        /// </summary>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int UpdateChapter(long i_book_id, long i_chapter_id, string i_chapter_url, BookUrlInfo i_book_url)
        {
            try
            {
                return m_boo_dao.UpdateChapter(i_book_id, i_chapter_id, i_chapter_url, i_book_url);
            }
            catch (Exception ex)
            {
                LogHelper.Error("更新小说下载状态失败" + ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 获取站点信息
        /// </summary>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        public SiteInfo GetSiteInfo(int i_site_id)
        {
            try
            {
                return m_boo_dao.GetTableName(i_site_id);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取站点信息失败" + ex.ToString());
                return null;
            }
        }

        
        /// <summary>
        /// 获取小说的章节地址列表
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public List<BookUrlInfo> GetBookUrlByBookId(long i_book_id)
        {
            try
            {
                return m_boo_dao.GetBookUrlByBookId(i_book_id);
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说URL失败" + ex.ToString());
                return null;
            }
        }

           /// <summary>
        /// 添加小说URL
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public int AddBookUrl(BookUrlInfo i_book_url)
        {
            try
            {
                return m_boo_dao.AddBookUrl(i_book_url);
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加小说URL失败" + ex.ToString());
                return -1;
            }
        }
    }
}
